#include "ChessBoardImp2.h"
#include "ChessBoardWidget.h"
#include "ChessBoard.h"
#include <iostream>

void ChessBoardImp2::paintBoard(ChessBoardWidget* widget){

    int width = getAttribute("width");
    int height = getAttribute("height");
    int widthMargin = getAttribute("widthMargin");
    int heightMargin = getAttribute("heightMargin");
    int blockWidth = getAttribute("blockWidth");
    int blockHeight = getAttribute("blockHeight");
    int blockWidthNum = getAttribute("blockWidthNum");
    int blockHeightNum = getAttribute("blockHeightNum");

    width = blockWidth*blockWidthNum+2*widthMargin;
    height = blockHeight*blockHeightNum+2*heightMargin;
    setAttribute("width",width);
    setAttribute("height",height);
    widget->resize(width,height);
    QPainter painter(widget);
    painter.setBrush(QColor(255,127,0));
    painter.drawRect(0, 0, width-1, height-1);

    for(int i=0;i<=blockWidthNum;i++){
        int x = i*blockWidth+widthMargin;
        int y = heightMargin;
        painter.drawLine(x,y,x,y+blockHeight*blockHeightNum);
    }
    for(int j=0;j<=blockHeightNum;j++){
        int x = widthMargin;
        int y = j*blockHeight+heightMargin;
        painter.drawLine(x,y,x+blockWidth*blockWidthNum,y);
    }

    painter.translate(widthMargin-blockWidth/2,heightMargin-blockHeight/2);
    //draw the chess on the board
    std::vector< std::vector<Chess*> > chessBoardState = (*(widget->getChessBoard()->getChessBoardInstance()));
    for(int i=0;i<blockHeightNum;i++){
        for(int j=0;j<blockWidthNum;j++){
            if(chessBoardState[i][j]!=NULL){
                std::string s = chessBoardState[i][j]->getAttribute("img");
                QImage chess(s.c_str());
                chess = chess.scaled(blockWidth*0.85,blockHeight*0.85,Qt::KeepAspectRatio);
                int shift_x = (blockWidth - chess.width())/2+1;
                int shift_y = (blockHeight - chess.height())/2+1;
                painter.drawImage(shift_x+j*blockWidth,shift_y+i*blockHeight,chess);
            }
        }
    }
}

QPoint ChessBoardImp2::getPosition(QPoint& p){

    int x = p.x();
    int y = p.y();
    int blockWidth = getAttribute("blockWidth");
    int blockHeight = getAttribute("blockHeight");
    int blockWidthNum = getAttribute("blockWidthNum");
    int blockHeightNum = getAttribute("blockHeightNum");

    x += blockWidth/2;
    y += blockHeight/2;
    x = x/blockWidth;
    y = y/blockHeight;

    if((x>=0&&x<=blockWidthNum) && (y>=0 && y<=blockHeightNum))
        return QPoint(x,y);
    else
        return QPoint(-1,-1);

    return QPoint(x,y);
}

